package com.yuncheng.spcyApi.busService;

import cn.hutool.core.collection.CollectionUtil;
import com.yuncheng.spcyApi.dto.sqsx.SqsxQueryStatDto;
import com.yuncheng.spcyApi.mapper.SpcySqsxXpjlMapper;
import com.yuncheng.spcyApi.vo.sys.UserNameVo;
import com.yuncheng.vo.CurrentUserVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.flow.*;
import com.yuncheng.spcyApi.constant.jcy.JcydjbConstant;
import com.yuncheng.spcyApi.entity.SpcyRsBhgz;
import com.yuncheng.spcyApi.entity.SpcySqsxXpjl;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.flow.SpcyFlowConstant;
import com.yuncheng.spcyApi.mapper.SpcyFlowMapper;
import com.yuncheng.spcyApi.mapper.SpcyRsHcyMapper;
import com.yuncheng.spcyApi.service.ISpcyRsBhgzService;
import com.yuncheng.spcyApi.service.ISpcySqsxXpjlService;
import com.yuncheng.spcyApi.service.IYcSysUserService;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.vo.common.StartEndTimeVo;
import com.yuncheng.spcyApi.vo.jcy.RsHcyVo;
import com.yuncheng.spcyApi.vo.spcy.SpcyFlowVo;
import com.yuncheng.spcyApi.vo.spcy.SpcyJobVo;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component(value = "spcyTjService")
public class SpcyTjService {
    @Resource
    @Lazy
    private IYcSysUserService ycSysUserService;

    @Resource
    @Lazy
    private SpcyFlowMapper spcyFlowMapper;

    @Resource
    @Lazy
    private ISpcyRsBhgzService spcyRsBhgzService;

    @Resource
    @Lazy
    private ISpcySqsxXpjlService spcySqsxXpjlService;

    @Resource
    @Lazy
    private SpcyRsHcyMapper spcyRsHcyMapper;

    @Resource
    private SpcySqsxXpjlMapper spcySqsxXpjlMapper;

    /**
     * 查询统计 - 审评查验流程 - 各环节数量 - 按科室进行
     */
    public Map queryEachDeptTjData(String fywflcode, StartEndTimeVo startEndTimeVo){
        boolean onlyCurrentUser = false; // 不查询个人
        Map resultMaps = new HashMap();

        String deptNameAbbr = SpcyConstant.getYwclNameByCode(fywflcode);// 获取对应的科室简称
        String deptName = ""; // 科室名
        List<YcSysUser> userList = ycSysUserService.list(new LambdaQueryWrapper<YcSysUser>()
                .like(StringUtils.isNotBlank(deptNameAbbr),YcSysUser::getOrgName, deptNameAbbr));
        if (CollectionUtils.isNotEmpty(userList)){
            deptName = userList.get(0).getOrgName();
        }

        List<Map> listMap = new ArrayList<>();
        List<String> ypscNodes = new ArrayList<>();

        // 药品生产
        if (fywflcode.equals(SpcyConstant.YWFL_CODE_YPSC)){
            ypscNodes = Arrays.asList(YpscFlowConstant.NODENAME.split(","));

        }
        else if (fywflcode.equals(SpcyConstant.YWFL_CODE_YPJY)){
            // 药品流通
            ypscNodes = Arrays.asList(YpltFlowConstant.NODENAME.split(","));

        }
        else if (fywflcode.equals(SpcyConstant.YWFL_CODE_YPZC)){
            // 药品注册
            ypscNodes = new ArrayList<>(Arrays.asList(YpzcFlowConstant.NODENAME.split(",")));
            ypscNodes.add(YlqxFlowConstant.HJMC_SP_FASH);
            ypscNodes.add(YlqxFlowConstant.HJMC_SP_FASP);
            ypscNodes.add(YlqxFlowConstant.HJMC_JSSP);

        }
        else if (fywflcode.equals(SpcyConstant.YWFL_CODE_YLQX)){
            // 医疗器械
            ypscNodes = new ArrayList<>(Arrays.asList(YlqxFlowConstant.NODENAME.split(",")));
            ypscNodes.add(YlqxFlowConstant.HJMC_SP_FASH);
            ypscNodes.add(YlqxFlowConstant.HJMC_SP_FASP);
            ypscNodes.add(YlqxFlowConstant.HJMC_JSSP);

        }else if (fywflcode.equals(SpcyConstant.YWFL_CODE_HZP)){
            // 化妆品
            ypscNodes = new ArrayList<>(Arrays.asList(HzpFlowConstant.NODENAME.split(",")));
            ypscNodes.add(YlqxFlowConstant.HJMC_SP_FASH);
            ypscNodes.add(YlqxFlowConstant.HJMC_SP_FASP);
            ypscNodes.add(YlqxFlowConstant.HJMC_JSSP);
        }

        // 药品生产 - 所有环节名称

        SpcyFlowVo ypscFlowVo = new SpcyFlowVo();
        ypscFlowVo.setFywflcode(fywflcode);
        ypscFlowVo.setFlcmc(YpscFlowConstant.LCMC_LIKE_SPCYLC);
        if (startEndTimeVo.getStartTime() != null){
            ypscFlowVo.setStartTime(startEndTimeVo.getStartTime());
        }
        if (startEndTimeVo.getEndTime() != null){
            ypscFlowVo.setEndTime(startEndTimeVo.getEndTime());
        }
        List<SpcyFlowVo> ypscSpcyFlowList = spcyFlowMapper.flowJkList(onlyCurrentUser, null, ypscFlowVo);

        Map resultMap = null;
        for (String node : ypscNodes) {
            resultMap = new HashMap();
            int count = 0; // 办理总量
            int dbsl = 0; // 待办数量
            int ybsl = 0; // 已办数量
            int dbcqs = 0; // 待办超期数

            if (CollectionUtils.isNotEmpty(ypscSpcyFlowList)) {
                count = ypscSpcyFlowList.stream()
                        .filter(f -> StringUtils.isNotBlank(f.getFhjmc())
                                && f.getFhjmc().equals(node)
                        )
                        .collect(
                                Collectors.collectingAndThen(
                                        Collectors.toCollection(
                                                () -> new TreeSet<>(
                                                        Comparator.comparing(o -> o.getSqsxid())
                                                )
                                        ), ArrayList<SpcyFlowVo>::new
                                )
                        )
                        .size();

                dbsl = ypscSpcyFlowList.stream()
                        .filter(f -> StringUtils.isNotBlank(f.getFhjmc())
                                && f.getFhjmc().equals(node)
                                && StringUtils.isNotBlank(f.getFblzt())
                                && (f.getFblzt().equals(SpcyConstant.BLZT_DB) || f.getFblzt().equals(SpcyConstant.BLZT_TH))
                        )
                        .collect(
                                Collectors.collectingAndThen(
                                        Collectors.toCollection(
                                                () -> new TreeSet<>(
                                                        Comparator.comparing(o -> o.getSqsxid())
                                                )
                                        ), ArrayList<SpcyFlowVo>::new
                                )
                        )
                        .size();

                ybsl = ypscSpcyFlowList.stream()
                        .filter(f -> StringUtils.isNotBlank(f.getFhjmc())
                                && f.getFhjmc().equals(node)
                                && StringUtils.isNotBlank(f.getFblzt())
                                && f.getFblzt().equals(SpcyConstant.BLZT_YB)
                        )
                        .collect(
                                Collectors.collectingAndThen(
                                        Collectors.toCollection(
                                                () -> new TreeSet<>(
                                                        Comparator.comparing(o -> o.getSqsxid())
                                                )
                                        ), ArrayList<SpcyFlowVo>::new
                                )
                        )
                        .size();

                Date nowDate = new Date();
                dbcqs = ypscSpcyFlowList.stream()
                        .filter(f -> StringUtils.isNotBlank(f.getFhjmc())
                                        && f.getFhjmc().equals(node)
                                        && StringUtils.isNotBlank(f.getFblzt())
                                        && (f.getFblzt().equals(SpcyConstant.BLZT_DB) || f.getFblzt().equals(SpcyConstant.BLZT_TH))
                                        && ((f.getFjzrq() != null
                                        && f.getFyssj() != null
                                        && f.getFyssj().compareTo(f.getFjzrq()) > 0
                                ) ||
                                        (f.getFjzrq() != null
                                                && f.getFyssj() == null
                                                && nowDate.compareTo(f.getFjzrq()) > 0
                                        ))
                        )
                        .collect(
                                Collectors.collectingAndThen(
                                        Collectors.toCollection(
                                                () -> new TreeSet<>(
                                                        Comparator.comparing(o -> o.getSqsxid())
                                                )
                                        ), ArrayList<SpcyFlowVo>::new
                                )
                        )
                        .size();

            }

            resultMap.put("deptName",deptName);
            resultMap.put("node",node); // 环节名称
            resultMap.put("count",count); // 办理总量
            resultMap.put("dbsl",dbsl); // 待办数量
            resultMap.put("ybsl",ybsl); // 已办数量
            resultMap.put("dbcqs",dbcqs); // 待办超期数量

            listMap.add(resultMap);
        }

        resultMaps.put("deptName",deptName);
        resultMaps.put("tjList",listMap);
        return resultMaps;
    }

    public Map queryEachDeptTjDataNew(String fywflcode, String deptName, StartEndTimeVo startEndTimeVo){
        Map resultMaps = new HashMap();

        List<Map> listMap = new ArrayList<>();
        Map resultMap = null;

        SpcyFlowVo selectBeanPar = new SpcyFlowVo();
        selectBeanPar.setFywflcode(fywflcode);
        selectBeanPar.setFlcmc(SpcyFlowConstant.LCMC_LIKE_SPCYLC);
        if (startEndTimeVo.getStartTime() != null){
            selectBeanPar.setStartTime(startEndTimeVo.getStartTime());
        }
        if (startEndTimeVo.getEndTime() != null){
            selectBeanPar.setEndTime(startEndTimeVo.getEndTime());
        }
        List<SpcyJobVo> jobList = spcyFlowMapper.selectFlowStat(null, null, selectBeanPar);

        SpcyFlowEnum[] nodeList = SpcyFlowEnum.values();
        for (int i = 0; i < nodeList.length; i++) {
            resultMap = new HashMap();
            String node =  nodeList[i].name();

            /*int count = jobList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFhjmc())
                            && f.getFhjmc().equals(node)
                    )
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();*/

            int dbsl = jobList.stream()
                    .filter(f -> f.getFhjmc().equals(node)
                            &&
                            !f.getFblzt().equals(SpcyConstant.BLZT_YB)
                    )
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            int ybsl = jobList.stream()
                    .filter(f -> f.getFhjmc().equals(node)
                            &&
                            f.getFblzt().equals(SpcyConstant.BLZT_YB)
                    )
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            int dbcqs = jobList.stream()
                    .filter(f -> f.getFhjmc().equals(node)
                            &&
                            !f.getFblzt().equals(SpcyConstant.BLZT_YB)
                            && StringUtils.isNotBlank(f.getFksyts())
                            && Double.parseDouble(f.getFksyts()) < 0
                    )
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            resultMap.put("deptName",deptName);
            resultMap.put("node", node); // 环节名称
            resultMap.put("count", (dbsl + ybsl)); // 办理总量
            resultMap.put("dbsl", dbsl); // 待办数量
            resultMap.put("ybsl", ybsl); // 已办数量
            resultMap.put("dbcqs", dbcqs); // 待办超期数量

            listMap.add(resultMap);
        }


        resultMaps.put("deptName",deptName);
        resultMaps.put("tjList",listMap);
        return resultMaps;
    }

    /**
     * 查询统计 - 每个科室 - 每个人的审评查验流程 - 统计数据
     */
    public Map queryEachDeptAndPersonTjData(String fywflcode,StartEndTimeVo startEndTimeVo, boolean onlyCurrentUser){
//        boolean onlyCurrentUser = false; // 不查询个人
        Map resultMaps = new HashMap();
        List<Map> listMap = new ArrayList<>();
        List<String> userNameList = new ArrayList<>(); // 用户Id
        List<YcSysUser> userList = new ArrayList<>();
        String deptNameAbbr = SpcyConstant.getYwclNameByCode(fywflcode);// 获取对应的科室简称
        String deptName = ""; // 部门名称
        CurrentUserVo user = null;

        /** 查询对应科室简称下的所有用户 */
        LambdaQueryWrapper<YcSysUser> queryWrapper = new LambdaQueryWrapper<YcSysUser>()
                .like(StringUtils.isNotBlank(deptNameAbbr), YcSysUser::getOrgName, deptNameAbbr);
        // 是否只查询个人
        if (onlyCurrentUser){
            CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
            if (currentUser == null){
                throw new BusinessException("当前登录已失效，请重新登录");
            }
            user = currentUser;
            queryWrapper.eq(YcSysUser::getId, currentUser.getId());
        }
        userList = ycSysUserService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(userList)){
            deptName = userList.get(0).getOrgName();
            userNameList = userList.stream().map(YcSysUser::getRealname).collect(Collectors.toList());
        }

        SpcyFlowVo ypscFlowVo = new SpcyFlowVo();
        ypscFlowVo.setFywflcode(fywflcode);
        ypscFlowVo.setFlcmc(YpscFlowConstant.LCMC_LIKE_SPCYLC);
        if (startEndTimeVo.getStartTime() != null){
            ypscFlowVo.setStartTime(startEndTimeVo.getStartTime());
        }
        if (startEndTimeVo.getEndTime() != null){
            ypscFlowVo.setEndTime(startEndTimeVo.getEndTime());
        }
        List<SpcyFlowVo> ypscSpcyFlowList = spcyFlowMapper.flowJkList(onlyCurrentUser, user, ypscFlowVo);

        if (CollectionUtils.isNotEmpty(userNameList)) {
            Map resultMap = null;
            for (String username : userNameList) {
                resultMap = new HashMap();
                int count = 0; // 办理总量
                int dbsl = 0; // 待办数量
                int ybsl = 0; // 已办数量
                int dbcqs = 0; // 超期数

                if (CollectionUtils.isNotEmpty(ypscSpcyFlowList)) {
                    count = ypscSpcyFlowList.stream()
                            .filter(f -> StringUtils.isNotBlank(f.getFblr())
                                    && f.getFblr().contains(username)
                            )
                            .collect(
                                    Collectors.collectingAndThen(
                                            Collectors.toCollection(
                                                    () -> new TreeSet<>(
                                                            Comparator.comparing(o -> o.getSqsxid())
                                                    )
                                            ), ArrayList<SpcyFlowVo>::new
                                    )
                            )
                            .size();

                    dbsl = ypscSpcyFlowList.stream()
                            .filter(f -> StringUtils.isNotBlank(f.getFdbr())
                                    && f.getFdbr().contains(username)
                                    && StringUtils.isNotBlank(f.getFblzt())
                                    && (f.getFblzt().equals(SpcyConstant.BLZT_DB) || f.getFblzt().equals(SpcyConstant.BLZT_TH))
                            )
                            .collect(
                                    Collectors.collectingAndThen(
                                            Collectors.toCollection(
                                                    () -> new TreeSet<>(
                                                            Comparator.comparing(o -> o.getSqsxid())
                                                    )
                                            ), ArrayList<SpcyFlowVo>::new
                                    )
                            )
                            .size();

                    ybsl = ypscSpcyFlowList.stream()
                            .filter(f -> StringUtils.isNotBlank(f.getFblr())
                                    && f.getFblr().contains(username)
                                    && StringUtils.isNotBlank(f.getFblzt())
                                    && f.getFblzt().equals(SpcyConstant.BLZT_YB)
                            )
                            .collect(
                                    Collectors.collectingAndThen(
                                            Collectors.toCollection(
                                                    () -> new TreeSet<>(
                                                            Comparator.comparing(o -> o.getSqsxid())
                                                    )
                                            ), ArrayList<SpcyFlowVo>::new
                                    )
                            )
                            .size();

                    Date nowDate = new Date();
                    dbcqs = ypscSpcyFlowList.stream()
                            .filter(f -> StringUtils.isNotBlank(f.getFdbr())
                                            && f.getFdbr().contains(username)
                                            && StringUtils.isNotBlank(f.getFblzt())
                                            && (f.getFblzt().equals(SpcyConstant.BLZT_DB) || f.getFblzt().equals(SpcyConstant.BLZT_TH))
                                            && ((f.getFjzrq() != null
                                            && f.getFyssj() != null
                                            && f.getFyssj().compareTo(f.getFjzrq()) > 0
                                    )
                                            || (f.getFjzrq() != null
                                            && f.getFyssj() == null
                                            && nowDate.compareTo(f.getFjzrq()) > 0
                                    ))
                            )
                            .collect(
                                    Collectors.collectingAndThen(
                                            Collectors.toCollection(
                                                    () -> new TreeSet<>(
                                                            Comparator.comparing(o -> o.getSqsxid())
                                                    )
                                            ), ArrayList<SpcyFlowVo>::new
                                    )
                            )
                            .size();

                }

                resultMap.put("deptName", deptName); // 姓名
                resultMap.put("username", username); // 姓名
                resultMap.put("count", count); // 办理总量
                resultMap.put("dbsl", dbsl); // 待办数量
                resultMap.put("ybsl", ybsl); // 已办数量
                resultMap.put("dbcqs", dbcqs); // 待办超期数量

                listMap.add(resultMap);
            }
        }
        resultMaps.put("deptName",deptName);
        resultMaps.put("tjList", listMap);

        return resultMaps;
    }

    public Map queryEachDeptAndPersonTjDataNew(String fywflcode, StartEndTimeVo startEndTimeVo, boolean onlyCurrentUser){
        Map resultMaps = new HashMap();
        List<Map> listMap = new ArrayList<>();
        List<String> userNameList = new ArrayList<>(); // 用户Id
        List<YcSysUser> userList = new ArrayList<>();

        String deptName = GetCurrentUserUtils.getCurrentUserOrgName(); // 部门名称

        String userid = null;
        /** 查询对应科室简称下的所有用户 */
        // 是否只查询个人
        if (onlyCurrentUser){
            userid = GetCurrentUserUtils.getCurrentUserId();
        }else {
            userList = ycSysUserService.getDeptIndexUserList(GetCurrentUserUtils.getCurrentUserOrgId());
        }

        SpcyFlowVo selectBeanPar = new SpcyFlowVo();
        selectBeanPar.setFywflcode(fywflcode);
        selectBeanPar.setFlcmc(SpcyFlowConstant.LCMC_LIKE_SPCYLC);
        if (startEndTimeVo.getStartTime() != null){
            selectBeanPar.setStartTime(startEndTimeVo.getStartTime());
        }
        if (startEndTimeVo.getEndTime() != null){
            selectBeanPar.setEndTime(startEndTimeVo.getEndTime());
        }
        List<SpcyJobVo> jobList = spcyFlowMapper.selectFlowStat(userid, null, selectBeanPar);

        Map resultMap = null;
        for (YcSysUser user : userList) {
            resultMap = new HashMap();
            int count = 0; // 办理总量
            int dbsl = 0; // 待办数量
            int ybsl = 0; // 已办数量
            int dbcqs = 0; // 超期数

            /*count = jobList.stream()
                    .filter(f -> f.getFdbrid().contains(user.getId()))
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();*/

            dbsl = jobList.stream()
                    .filter(f ->
                            f.getFdbrid().contains(user.getId())
                            &&
                            !f.getFblzt().equals(SpcyConstant.BLZT_YB)
                    )
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            ybsl = jobList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFblrid()) && f.getFblrid().equals(user.getId())
                            &&
                            f.getFblzt().equals(SpcyConstant.BLZT_YB)
                    )
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            dbcqs = jobList.stream()
                    .filter(f ->
                            f.getFdbrid().contains(user.getId())
                            &&
                            !f.getFblzt().equals(SpcyConstant.BLZT_YB)
                            && StringUtils.isNotBlank(f.getFksyts())
                            && Double.parseDouble(f.getFksyts()) < 0
                    )
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            count = dbsl + ybsl;

            resultMap.put("deptName", deptName); // 姓名
            resultMap.put("username", user.getRealname()); // 姓名
            resultMap.put("count", count); // 办理总量
            resultMap.put("dbsl", dbsl); // 待办数量
            resultMap.put("ybsl", ybsl); // 已办数量
            resultMap.put("dbcqs", dbcqs); // 待办超期数量

            if (count>0) {
                listMap.add(resultMap);
            }
        }

        resultMaps.put("deptName",deptName);
        resultMaps.put("tjList", listMap);
        return resultMaps;
    }

    /**
     * 查询统计 - 检查出勤量 - 年度 - 业务分类
     * @param fywflcode 业务分类编码 (不能为空)
     * @param years 多个年份（逗号分割） (可为空)
     * @param jclxs 检查类型 (可为空)
     * @param isSd 是否属地 (true/false)
     * @param isYd 是否异地 (true/false)
     * @return
     */
    public List<List<String>> queryHcyCqlInTjData(String fywflcode,String years,String jclxs,String fgzdw,boolean isSd,boolean isYd) {
        if (StringUtils.isBlank(years)){
            years = DateConversionUtils.DateToYear(new Date());
        }

        // 检查类型
        List<String> jclxList = new ArrayList<>();
        if (StringUtils.isNotBlank(jclxs)) {
            jclxList = Arrays.asList(jclxs.split(",|，"));
        } else {
            List<SpcyRsBhgz> bhgzList = spcyRsBhgzService.list(new LambdaQueryWrapper<SpcyRsBhgz>()
                    .eq(StringUtils.isNotBlank(fywflcode), SpcyRsBhgz::getFywflcode, fywflcode)
                    .isNull(SpcyRsBhgz::getFtype2)
                    .isNull(SpcyRsBhgz::getFhz)
            );
            if (CollectionUtils.isNotEmpty(bhgzList)){
                jclxList = bhgzList.stream().map(SpcyRsBhgz::getFtype1).collect(Collectors.toList());
            }
        }

        // 年份数组
        List<String> yearList = Arrays.asList(years.split(",|，"));

        // 核查员
        RsHcyVo hcyVo = new RsHcyVo();
        hcyVo.setFjcyxl(JcydjbConstant.getJcyXlByYwflcode(fywflcode));
        hcyVo.setFusertype(SpcyConstant.HCY_USERTYPE_JCY); // 检查员
        if (StringUtils.isNotBlank(fgzdw)){
            hcyVo.setFgzdw(fgzdw);
        }
        List<RsHcyVo> hcyList = spcyRsHcyMapper.getRsHcyList(hcyVo);

        List<List<String>> listMap = new ArrayList<>();
        List<String> titleList = new ArrayList<>(); // 标题
        titleList.add("序号");
        titleList.add("姓 名");
        titleList.add("单 位");

        for (String year : yearList){
            for (String jclx : jclxList){
                StringBuffer bt = new StringBuffer(year);
                bt.append("年");
                bt.append("参加");
                bt.append(jclx);
                bt.append("次数");
                titleList.add(bt.toString());
                if (isSd) {
                    String sd = "（属地）";
                    titleList.add(bt.toString()+sd);
                }
                if (isYd) {
                    String yd = "（异地）";
                    titleList.add(bt.toString()+yd);
                }
            }
        }
        titleList.add("合计");
        listMap.add(titleList);

        List<String> dataList = new ArrayList<>(); // 数据
        if (CollectionUtils.isNotEmpty(hcyList)) {
            int i = 0;
            for (RsHcyVo hcy : hcyList) {

                // 当前核查员不存在选派记录
                List<SpcySqsxXpjl> xpjlList = spcySqsxXpjlService.list(new LambdaQueryWrapper<SpcySqsxXpjl>()
                        .eq(StringUtils.isNotBlank(hcy.getFuserid()), SpcySqsxXpjl::getFuserid, hcy.getFuserid())
                        .eq(SpcySqsxXpjl::getFspcylx, SpcyConstant.FLOW_TYPE_CY)
                        .eq(SpcySqsxXpjl::getFhbjczt, 0)
                );
                if (CollectionUtils.isEmpty(xpjlList)){
                    continue;
                }

                dataList = new ArrayList<>();
                i = i + 1;
                dataList.add(String.valueOf(i));
                dataList.add(hcy.getRealname()); // 姓名
                dataList.add(hcy.getFgzdw()); // 单位

                for (String year : yearList) {
                    for (String jclx : jclxList) {
                        // 核查员 是否存在选派记录
                        if (CollectionUtils.isNotEmpty(xpjlList)){

                            // 年份 + 检查类型 选派记录
                            List<SpcySqsxXpjl> yearXpjlList = xpjlList.stream()
                                    .filter(f ->
                                            f.getFzpsj() != null
                                                    && DateConversionUtils.getYearByDate(f.getFzpsj()) == Integer.valueOf(year)
                                                    && StringUtils.isNotBlank(f.getFrwlx())
                                                    && f.getFrwlx().equals(jclx)
                                    )
                                    .collect(
                                            Collectors.collectingAndThen(
                                                    Collectors.toCollection(
                                                            () -> new TreeSet<>(
                                                                    Comparator.comparing(o -> o.getFsqsxid())
                                                            )
                                                    ), ArrayList<SpcySqsxXpjl>::new
                                            )
                                    );
                            dataList.add(String.valueOf(yearXpjlList.size()));

                            boolean isYearXpjl = false; // 是否存在 年度+检查类型 的选派记录
                            if (CollectionUtils.isNotEmpty(yearXpjlList)){
                                isYearXpjl = true;
                            }

                            // 属地 + 年度 + 检查类型
                            if (isSd) {
                                // 属地
                                if (isYearXpjl){
                                    int size = yearXpjlList.stream()
                                            .filter(f -> StringUtils.isNotBlank(f.getFssqy())
                                                    && StringUtils.isNotBlank(f.getFjcqy())
                                                    && f.getFjcqy().contains(f.getFssqy())
                                            )
                                            .collect(
                                                    Collectors.collectingAndThen(
                                                            Collectors.toCollection(
                                                                    () -> new TreeSet<>(
                                                                            Comparator.comparing(o -> o.getFsqsxid())
                                                                    )
                                                            ), ArrayList<SpcySqsxXpjl>::new
                                                    )
                                            )
                                            .size();
                                    dataList.add(String.valueOf(size));
                                }else {
                                    dataList.add("0");
                                }
                            }

                            // 异地 + 年度 + 检查类型
                            if (isYd) {
                                // 异地
                                if (isYearXpjl){
                                    int size = yearXpjlList.stream()
                                            .filter(f -> (
                                                    StringUtils.isBlank(f.getFssqy())
                                                    &&
                                                    StringUtils.isBlank(f.getFjcqy())
                                                    )
                                                    || (StringUtils.isBlank(f.getFssqy())
                                                    &&
                                                    StringUtils.isNotBlank(f.getFjcqy())
                                                    )
                                                    || (StringUtils.isNotBlank(f.getFssqy())
                                                    &&
                                                    StringUtils.isBlank(f.getFjcqy())
                                                    )
                                                    || (StringUtils.isNotBlank(f.getFssqy())
                                                    && StringUtils.isNotBlank(f.getFjcqy())
                                                    && !f.getFjcqy().contains(f.getFssqy())
                                                    )
                                            )
                                            .collect(
                                                    Collectors.collectingAndThen(
                                                            Collectors.toCollection(
                                                                    () -> new TreeSet<>(
                                                                            Comparator.comparing(o -> o.getFsqsxid())
                                                                    )
                                                            ), ArrayList<SpcySqsxXpjl>::new
                                                    )
                                            )
                                            .size();
                                    dataList.add(String.valueOf(size));
                                }else {
                                    dataList.add("0");
                                }
                            }
                        } else {
                            // 年度 + 检查类型
                            dataList.add("0");

                            // 属地
                            if (isSd) {
                                dataList.add("0");
                            }

                            // 异地
                            if (isYd) {
                                dataList.add("0");
                            }
                        }
                    }
                }
                dataList.add(String.valueOf(xpjlList.size())); // 合计
                listMap.add(dataList);
            }
        }

        return listMap;
    }

    /**
     * 查询统计-年度-检查类型
     * @param fywflcode 业务分类编码 (不能为空)
     * @param years 多个年份（逗号分割） (可为空)
     * @param jclxs 检查类型 (可为空)
     */
    public List<List<String>> queryJclxYearTjData(String fywflcode,String years,String jclxs){
        List<List<String>> resultList = new ArrayList<>(); // 二维表数组

        List<String> titleList = new ArrayList<>(); // 标题
        List<String> dataList = new ArrayList<>(); // 数据

        if (StringUtils.isBlank(years)){
            years = DateConversionUtils.DateToYear(new Date());
        }

        // 检查类型
        List<String> jclxList = new ArrayList<>();
        if (StringUtils.isNotBlank(jclxs)) {
            jclxList = Arrays.asList(jclxs.split(",|，"));
        } else {
            List<SpcyRsBhgz> bhgzList = spcyRsBhgzService.list(new LambdaQueryWrapper<SpcyRsBhgz>()
                    .eq(StringUtils.isNotBlank(fywflcode), SpcyRsBhgz::getFywflcode, fywflcode)
                    .isNull(SpcyRsBhgz::getFtype2)
                    .isNull(SpcyRsBhgz::getFhz)
            );
            if (CollectionUtils.isNotEmpty(bhgzList)){
                jclxList = bhgzList.stream().map(SpcyRsBhgz::getFtype1).collect(Collectors.toList());
            }
        }

        // 年份数组
        List<String> yearList = Arrays.asList(years.split(",|，"));

        List<SpcySqsxXpjl> xpjlList = spcySqsxXpjlService.list(new LambdaQueryWrapper<SpcySqsxXpjl>()
                .eq(SpcySqsxXpjl::getFspcylx, SpcyConstant.FLOW_TYPE_CY)
                .eq(StringUtils.isNotBlank(fywflcode), SpcySqsxXpjl::getFywflcode, fywflcode)
                .eq(SpcySqsxXpjl::getFsftyxp,SpcyConstant.XPJL_SFTYXP_YES)
                .eq(SpcySqsxXpjl::getFhbjczt, 0));

        titleList.add("序号");
        titleList.add("年度");
        for (String jclx : jclxList){
            titleList.add(jclx+"(家)");
        }
        titleList.add("未知（家）");
        titleList.add("检查小计");
        resultList.add(titleList);

        int i = 0;
        for (String year : yearList) {
            dataList = new ArrayList<>();
            i = i + 1;
            dataList.add(String.valueOf(i));
            dataList.add(year);
            for (String jclx : jclxList) {
                if (CollectionUtils.isNotEmpty(xpjlList)) {
                    int c = 0;
                    List<SpcySqsxXpjl> countList = xpjlList.stream()
                            .filter(f -> StringUtils.isNotBlank(f.getFrwlx())
                                    && f.getFrwlx().contains(jclx)
                                    && f.getFzpsj() != null
                                    && DateConversionUtils.getYearByDate(f.getFzpsj()) == Integer.valueOf(year)
                            )
                            .collect(
                                    Collectors.collectingAndThen(
                                            Collectors.toCollection(
                                                    () -> new TreeSet<>(
                                                            Comparator.comparing(o -> o.getFsqsxid())
                                                    )
                                            ), ArrayList<SpcySqsxXpjl>::new
                                    )
                            );
                    if (CollectionUtils.isNotEmpty(countList)) {
                        List<String> sqsxIdList = countList.stream().map(SpcySqsxXpjl::getFsqsxid).collect(Collectors.toList());
                        List<String> distSqsxIdList = sqsxIdList.stream().distinct().collect(Collectors.toList());
                        c = distSqsxIdList.size();
                    }

                    dataList.add(String.valueOf(c));
                }else {
                    dataList.add("0");
                }
            }

            // 未知 - 年度选派数量
            if (CollectionUtils.isNotEmpty(xpjlList)){
                int c = 0;
                List<SpcySqsxXpjl> yearXpjlList = xpjlList.stream()
                        .filter(f -> f.getFzpsj() != null
                                && DateConversionUtils.getYearByDate(f.getFzpsj()) == Integer.valueOf(year)
                                && StringUtils.isBlank(f.getFrwlx())
                        )
                        .collect(
                                Collectors.collectingAndThen(
                                        Collectors.toCollection(
                                                () -> new TreeSet<>(
                                                        Comparator.comparing(o -> o.getFsqsxid())
                                                )
                                        ), ArrayList<SpcySqsxXpjl>::new
                                )
                        );

                if (CollectionUtils.isNotEmpty(yearXpjlList)) {
                    List<String> sqsxIdList = yearXpjlList.stream().map(SpcySqsxXpjl::getFsqsxid).collect(Collectors.toList());
                    List<String> distSqsxIdList = sqsxIdList.stream().distinct().collect(Collectors.toList());
                    c = distSqsxIdList.size();
                }

                dataList.add(String.valueOf(c));
            }else {
                dataList.add("0");
            }

            // 小计 - 年度选派数量
            if (CollectionUtils.isNotEmpty(xpjlList)){
                int c = 0;
                List<SpcySqsxXpjl> yearXpjlList = xpjlList.stream()
                        .filter(f -> f.getFzpsj() != null
                                && DateConversionUtils.getYearByDate(f.getFzpsj()) == Integer.valueOf(year)
                                && StringUtils.isNotBlank(f.getFrwlx())
                        )
                        .collect(
                                Collectors.collectingAndThen(
                                        Collectors.toCollection(
                                                () -> new TreeSet<>(
                                                        Comparator.comparing(o -> o.getFsqsxid())
                                                )
                                        ), ArrayList<SpcySqsxXpjl>::new
                                )
                        );

                if (CollectionUtils.isNotEmpty(yearXpjlList)) {
                    List<String> sqsxIdList = yearXpjlList.stream().map(SpcySqsxXpjl::getFsqsxid).collect(Collectors.toList());
                    List<String> distSqsxIdList = sqsxIdList.stream().distinct().collect(Collectors.toList());
                    c = distSqsxIdList.size();
                }

                dataList.add(String.valueOf(c));
            }else {
                dataList.add("0");
            }

            resultList.add(dataList);
        }

        return resultList;
    }

    /**
     * 特药审评-查询统计-导出
     */
    public List<List<String>> genTyCxtjExport(List<SqsxQueryStatDto> statDataList){
        List<List<String>> resultList = new ArrayList<>(); // 二维表数组
        List<String> titleList = new ArrayList<>(); // 标题
        List<String> dataList = null; // 数据

        titleList.add("序号");
        titleList.add("事项名称");
        titleList.add("企业名称");
        titleList.add("产品名称");

        titleList.add("申请分类");
        titleList.add("注册分类");
        titleList.add("勤务分类");

        titleList.add("审评开始时间");
        titleList.add("审评结束时间");
        titleList.add("审评结果");
        resultList.add(titleList);

        // 数据
        int i = 0;
        for (SqsxQueryStatDto statData : statDataList){
            dataList = new ArrayList<>();
            i = i + 1;
            dataList.add(String.valueOf(i));
            dataList.add(statData.getFsxmc());
            dataList.add(statData.getFqymc());
            dataList.add(statData.getFcpmc());

            dataList.add(statData.getFsqfl());
            dataList.add(statData.getFzcfl());
            dataList.add(statData.getFqwfl());

            dataList.add(statData.getFcykssj() != null ? DateConversionUtils.DateToStringYYYYMMDD(statData.getFcykssj()) : "");
            dataList.add(statData.getFcyjssj() != null ? DateConversionUtils.DateToStringYYYYMMDD(statData.getFcyjssj()) : "");
            dataList.add(statData.getFzhjg());

            resultList.add(dataList);
        }

        return resultList;
    }

    /**
     * 构建-特药审评-多维度统计-根据不同维度统计结果
     * @param mapStatList 根据sql进行分组查询数据集
     * @param titleIndxList 表头内容字段
     * @param username 用户名 （存在专家第二列为 专家姓名列）
     * */
    public List<List<String>> genTydwdTj(int order, List<Map> mapStatList, List<String> titleIndxList, String username){
        List<String> dataList = null;
        List<List<String>> resultDataList = new ArrayList<>(mapStatList.size());

        if (CollectionUtil.isEmpty(mapStatList)){
            dataList = new ArrayList<>();

            dataList.add(String.valueOf(order));

            if (StringUtils.isNotBlank(username)){
                dataList.add(username);
            }

            for (String index : titleIndxList){
                dataList.add("");
            }

            resultDataList.add(dataList);
            return resultDataList;
        }

        /** 动态构建数据 */
        for (Map map : mapStatList){
            dataList = new ArrayList<>();

            dataList.add(String.valueOf(order));

            if (StringUtils.isNotBlank(username)){
                dataList.add(username);
            }

            for (String index : titleIndxList){
                try {
                    dataList.add(map.get(index.toUpperCase()).toString());
                }catch (Exception e){
                    dataList.add("");
                }
            }

            order++;

            resultDataList.add(dataList);
        }

        return resultDataList;
    }


    /**
     * 构建-特药审评-评价统计-年度评价率
     * */
    public List<List<String>> genTyPjStatYear(String year){
        List<Map> mapStatList = spcySqsxXpjlMapper.selectPjvYear(year, null);

        List<String> titleList = CollectionUtil.newArrayList(
                "序号",
                "年度",
                "优秀（人次）",
                "合格（人次）",
                "不合格（人次）",
                "合计"
        );

        List<List<String>> resultDataList = new ArrayList<>();
        resultDataList.add(titleList);

        List<String> dataList = new ArrayList<>();
        dataList.add("1");
        dataList.add(year);

        int data1V = 0;
        int data2V = 0;
        int data3V = 0;
        for (Map map : mapStatList){

            try {
                if ("优秀".equals(map.get("FZHPJ").toString())){
                    data1V = Integer.valueOf(map.get("C").toString());
                }
            }catch (Exception e){
            }

            try {
                if ("合格".equals(map.get("FZHPJ").toString())){
                    data2V = Integer.valueOf(map.get("C").toString());
                }
            }catch (Exception e){

            }

            try {
                if ("不合格".equals(map.get("FZHPJ").toString())){
                    data3V = Integer.valueOf(map.get("C").toString());
                }
            }catch (Exception e){

            }
        }

        dataList.add(String.valueOf(data1V));
        dataList.add(String.valueOf(data2V));
        dataList.add(String.valueOf(data3V));
        dataList.add(String.valueOf(data1V + data2V + data3V));

        resultDataList.add(dataList);

        return resultDataList;
    }

    /**
     * 构建-特药审评-评价统计-专家年度评价率
     */
    public List<List<String>> genTyPjTjZj(String year, List<UserNameVo> userList){
        List<String> titleList = CollectionUtil.newArrayList(
                "序号",
                "年度",
                "姓名",
                "单位",
                "优秀（人次）",
                "合格（人次）",
                "不合格（人次）",
                "合计"
        );

        List<List<String>> resultDataList = new ArrayList<>();
        resultDataList.add(titleList);

        int order = 1;
        for (UserNameVo user : userList) {

            List<Map> mapStatList = spcySqsxXpjlMapper.selectPjvYear(year, user.getId());

            List<String> dataList = new ArrayList<>();
            dataList.add(String.valueOf(order));
            dataList.add(year);
            dataList.add(user.getRealname());
            dataList.add(user.getFgzdw());

            int data1V = 0;
            int data2V = 0;
            int data3V = 0;
            for (Map map : mapStatList) {

                try {
                    if ("优秀".equals(map.get("FZHPJ").toString())) {
                        data1V = Integer.valueOf(map.get("C").toString());
                    }
                } catch (Exception e) {
                }

                try {
                    if ("合格".equals(map.get("FZHPJ").toString())) {
                        data2V = Integer.valueOf(map.get("C").toString());
                    }
                } catch (Exception e) {

                }

                try {
                    if ("不合格".equals(map.get("FZHPJ").toString())) {
                        data3V = Integer.valueOf(map.get("C").toString());
                    }
                } catch (Exception e) {

                }
            }

            dataList.add(String.valueOf(data1V));
            dataList.add(String.valueOf(data2V));
            dataList.add(String.valueOf(data3V));
            dataList.add(String.valueOf(data1V + data2V + data3V));

            resultDataList.add(dataList);
            order++;
        }

        return resultDataList;
    }

}
